import React, { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { FiMic, FiMicOff, FiPlus, FiX, FiShuffle } from 'react-icons/fi';
import { useApp } from '../contexts/AppContext';
import { wordValidator } from '../utils/wordValidator';
import { speechService } from '../utils/speechService';
import { toast } from 'react-hot-toast';

const WordInput: React.FC = () => {
  const { state, setSelectedWords, generateScene } = useApp();
  const [inputValue, setInputValue] = useState('');
  const [wordList, setWordList] = useState<string[]>([]);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [isListening, setIsListening] = useState(false);
  const [errors, setErrors] = useState<string[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);

  // 更新建议
  useEffect(() => {
    const newSuggestions = wordValidator.getWordSuggestions(inputValue, 'intermediate');
    setSuggestions(newSuggestions.map(s => s.word));
  }, [inputValue]);

  // 添加单词
  const addWord = (word: string) => {
    if (wordList.length >= 10) {
      toast.error('最多只能输入10个单词');
      return;
    }

    const { valid, errors: validationErrors } = wordValidator.validateWordList([word]);
    
    if (valid.length > 0 && !wordList.includes(valid[0])) {
      const newWordList = [...wordList, valid[0]];
      setWordList(newWordList);
      setSelectedWords(newWordList);
      setInputValue('');
      setErrors([]);
    } else if (validationErrors.length > 0) {
      setErrors(validationErrors);
    } else if (wordList.includes(word.toLowerCase())) {
      toast.error('该单词已存在');
    }
  };

  // 移除单词
  const removeWord = (index: number) => {
    const newWordList = wordList.filter((_, i) => i !== index);
    setWordList(newWordList);
    setSelectedWords(newWordList);
  };

  // 随机生成单词
  const generateRandomWords = () => {
    const randomWords = wordValidator.getRandomWordSet(5, 'intermediate');
    setWordList(randomWords);
    setSelectedWords(randomWords);
    toast.success('已为您智能生成词汇组合！');
  };

  // 语音输入
  const startVoiceInput = async () => {
    if (!speechService.isSupported()) {
      toast.error('您的浏览器不支持语音识别');
      return;
    }

    setIsListening(true);
    
    try {
      const result = await speechService.startListening();
      const words = result.transcript.split(' ').filter(word => word.trim());
      
      for (const word of words) {
        addWord(word.trim());
      }
      
      toast.success(`识别到: ${result.transcript}`);
    } catch (error) {
      toast.error('语音识别失败，请重试');
    } finally {
      setIsListening(false);
    }
  };

  // 停止语音输入
  const stopVoiceInput = () => {
    speechService.stopListening();
    setIsListening(false);
  };

  // 处理回车键
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && inputValue.trim()) {
      addWord(inputValue.trim());
    }
  };

  // 生成场景
  const handleGenerateScene = async () => {
    if (wordList.length < 3) {
      toast.error('至少需要 3 个单词才能生成场景');
      return;
    }
    
    await generateScene(wordList);
  };

  return (
    <div className="max-w-2xl mx-auto p-4 sm:p-6 space-y-4 sm:space-y-6">
      {/* 品牌标题 */}
      <motion.div 
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        className="text-center space-y-3 sm:space-y-4"
      >
        <div className="relative">
          <h1 className="text-4xl sm:text-5xl font-bold bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent" style={{ lineHeight: 2 }}>
            SceneLingo
          </h1>
          <motion.div
            initial={{ scale: 0, rotate: -180 }}
            animate={{ scale: 1, rotate: 0 }}
            transition={{ delay: 0.5, type: "spring", bounce: 0.4 }}
            className="absolute -top-1 sm:-top-2 -right-6 sm:-right-8 text-xl sm:text-2xl"
          >
            ✨
          </motion.div>
        </div>
        <div className="space-y-2">
          <p className="text-lg sm:text-xl font-medium text-gray-700">
            场景化英语学习新体验
          </p>
          <p className="text-gray-500 max-w-md mx-auto text-sm sm:text-base">
            输入词汇，AI为您构建沉浸式学习场景，让英语学习像看电影一样生动有趣
          </p>
        </div>
      </motion.div>

      {/* 输入区域 */}
      <motion.div 
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.2 }}
        className="bg-white rounded-xl shadow-lg p-4 sm:p-6 space-y-4"
      >
        <div className="flex flex-row gap-2">
          <div className="flex-1 relative">
            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="请输入英语单词，如: apple, book, happy..."
              className="w-full px-3 py-2.5 sm:px-4 sm:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all text-sm sm:text-base"
              disabled={state.isGeneratingScene}
            />
            
            {/* 错误信息 */}
            <AnimatePresence>
              {errors.length > 0 && (
                <motion.div
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -10 }}
                  className="absolute top-full mt-1 w-full bg-red-50 border border-red-200 rounded-lg p-2 text-xs sm:text-sm text-red-600"
                >
                  {errors.map((error, index) => (
                    <div key={index}>{error}</div>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>
          </div>
          
          {/* 操作按钮组 */}
          <div className="flex gap-1.5 sm:gap-2">
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={() => addWord(inputValue.trim())}
              disabled={!inputValue.trim() || state.isGeneratingScene}
              className="px-3 sm:px-4 py-2.5 sm:py-3 bg-gradient-to-r from-purple-600 to-blue-600 text-white rounded-lg sm:rounded-xl hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <FiPlus size={16} className="sm:w-5 sm:h-5" />
            </motion.button>
            
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={isListening ? stopVoiceInput : startVoiceInput}
              disabled={state.isGeneratingScene}
              className={`px-3 sm:px-4 py-2.5 sm:py-3 rounded-lg sm:rounded-xl transition-all ${
                isListening 
                  ? 'bg-red-500 text-white animate-pulse shadow-lg' 
                  : 'bg-gray-100 text-gray-600 hover:bg-gray-200 hover:shadow-md'
              }`}
            >
              {isListening ? <FiMicOff size={16} className="sm:w-5 sm:h-5" /> : <FiMic size={16} className="sm:w-5 sm:h-5" />}
            </motion.button>
          </div>
        </div>

        {/* 智能建议 */}
        {suggestions.length > 0 && inputValue && (
          <motion.div 
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-wrap gap-2 items-center"
          >
            <span className="text-xs sm:text-sm text-gray-500 font-medium">智能推荐:</span>
            {suggestions.slice(0, 5).map((suggestion) => (
              <motion.button
                key={suggestion}
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={() => addWord(suggestion)}
                className="px-2 sm:px-3 py-1 sm:py-1.5 bg-gradient-to-r from-purple-100 to-blue-100 text-purple-700 rounded-full text-xs sm:text-sm font-medium hover:from-purple-200 hover:to-blue-200 transition-all shadow-sm"
              >
                {suggestion}
              </motion.button>
            ))}
          </motion.div>
        )}
      </motion.div>

      {/* 已选择的单词 */}
      <AnimatePresence>
        {wordList.length > 0 && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -20 }}
            className="bg-white rounded-xl shadow-lg p-4 sm:p-6 space-y-4"
          >
            <div className="flex flex-col xs:flex-row xs:items-center xs:justify-between sm:flex-row sm:items-center sm:justify-between gap-3 xs:gap-2 sm:gap-0">
              <h3 className="text-base sm:text-lg font-semibold text-gray-800">
                我的单词库 ({wordList.length}/10)
              </h3>
              <motion.button
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
                onClick={generateRandomWords}
                disabled={state.isGeneratingScene}
                className="flex items-center justify-center xs:justify-start sm:justify-start gap-2 px-3 sm:px-4 py-2 bg-gradient-to-r from-gray-100 to-gray-200 text-gray-700 hover:from-purple-100 hover:to-blue-100 hover:text-purple-700 rounded-lg transition-all font-medium text-sm sm:text-base"
              >
                <FiShuffle size={14} className="sm:w-4 sm:h-4" />
                <span className="whitespace-nowrap">随机填充</span>
              </motion.button>
            </div>
            
            <div className="flex flex-wrap gap-2">
              {wordList.map((word, index) => (
                <motion.div
                  key={word}
                  initial={{ opacity: 0, scale: 0.8 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.8 }}
                  className="group flex items-center gap-1.5 xs:gap-2 sm:gap-2 px-2.5 xs:px-3 sm:px-4 py-1.5 xs:py-2 sm:py-2 bg-gradient-to-r from-indigo-100 via-purple-100 to-pink-100 rounded-full border border-indigo-200 hover:border-indigo-300 transition-all"
                >
                  <span className="text-indigo-700 font-semibold text-xs xs:text-sm sm:text-base">{word}</span>
                  <button
                    onClick={() => removeWord(index)}
                    className="text-indigo-400 hover:text-red-500 transition-colors group-hover:scale-110 transform"
                  >
                    <FiX size={12} className="xs:w-3.5 xs:h-3.5 sm:w-4 sm:h-4" />
                  </button>
                </motion.div>
              ))}
            </div>
            
            {/* 创建场景按钮 */}
            <motion.button
              whileHover={{ scale: 1.02 }}
              whileTap={{ scale: 0.98 }}
              onClick={handleGenerateScene}
              disabled={wordList.length < 3 || state.isGeneratingScene}
              className={`
                w-full py-2.5 xs:py-3 sm:py-4 rounded-lg xs:rounded-xl font-bold text-sm xs:text-base sm:text-lg transition-all duration-300
                ${wordList.length >= 3 && !state.isGeneratingScene
                  ? 'bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 text-white shadow-xl hover:shadow-2xl transform hover:-translate-y-1'
                  : 'bg-gradient-to-r from-gray-200 to-gray-300 text-gray-500 cursor-not-allowed'
                }
              `}
            >
              {state.isGeneratingScene ? (
                <div className="flex items-center justify-center gap-2">
                  <div className="w-3.5 xs:w-4 sm:w-5 h-3.5 xs:h-4 sm:h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  <span className="text-xs xs:text-sm sm:text-base">正在创建您的学习场景...</span>
                </div>
              ) : (
                <span className="text-xs xs:text-sm sm:text-base">🎬 开始沉浸式学习{wordList.length >= 3 ? '' : ` (还需${3 - wordList.length}个单词)`}</span>
              )}
            </motion.button>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};

export default WordInput;